import { reqCode, reqLogin, reqLogout, reqRegister, reqUserInfo } from "@/api"

const state = {
    token: localStorage.getItem('TOKEN'),
    code: '',
    userInfo: {}
}
const mutations = {
    // 登录
    USERLOGIN(state, data) {
        state.token = data
    },
    // 注册验证码
    GETCODE(state, data) {
        state.code = data
    },
    // 获取用户信息
    GETUSERINFO(state, data) {
        state.userInfo = data
    },
    // 退出
    USERLOGOUT(state) {
        state.token = ''
        state.userInfo = {}
        localStorage.removeItem("TOKEN")
    }
}
const actions = {
    // 登录
    async userLogin({ commit }, data) {
        const result = await reqLogin(data)
        console.log(result);
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            localStorage.setItem("TOKEN", result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    // 注册
    async userRegister({ commit }, data) {
        const result = await reqRegister(data)
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    // 获取注册验证码
    async getCode({ commit }, phone) {
        const result = await reqCode(phone)
        if (result.code === 200) {
            commit('GETCODE', result.data)
        } else {
            return Promise.reject(new Error("注册失败"))
        }

    },
    // 获取用户信息
    async getUserInfo({ commit }) {
        const result = await reqUserInfo()
        if (result.code === 200) {
            commit('GETUSERINFO', result.data)
        }
    },
    // 退出
    async userLogout({ commit }) {
        const result = await reqLogout()
        if (result.code === 200) {
            commit('USERLOGOUT')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
}
const getters = {
    userName(state) {
        return state.userInfo.name
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}